package com.david.reader.txt

import android.content.Context
import android.util.Log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.*

object TxtUtils {
    /**
     * 通过输入流开始分页，并存入数据库
     */
    fun getPagesFromFile(inputStream:InputStream, dataBase: TxtDataBase){
        CoroutineScope(Dispatchers.IO).launch {
            val bufferedReader = BufferedReader(InputStreamReader(inputStream))
            var line:String? = bufferedReader.readLine()
            while (line != null) {

//                while () {
//
//                }
//
//
                dataBase.txtPageDao()?.insertPage(TxtPage(0, 0, line))
                line = bufferedReader.readLine()
            }

        }

    }

    fun getPages(context:Context, dataBase: TxtDataBase){
        getPages(dataBase, context.assets.open("test.txt"))
    }


    fun getPages(dataBase: TxtDataBase, inputStream: InputStream){
        try {
            val pageLines = 18 //一页几行
            val lineTexts = 16 //每行字数
            val reader = BufferedReader(InputStreamReader(inputStream, "UTF-8"))
            var line: String? = null
//            val pages: ArrayList<String> = ArrayList()
            var tempPage = ""
            var tempLineCount = 0
            while (reader.readLine().also { line = it } != null) {
                println(line)
                var tempLine = line
                while (tempLine!!.length > 0) {
                    if (tempLine.length > lineTexts) {
                        println(tempLine.substring(0, lineTexts))
                        tempPage += tempLine.substring(0, lineTexts)
                        ++tempLineCount
                        tempLine = tempLine.substring(lineTexts)
                    } else {
                        println(tempLine)
                        tempPage += """
                    $tempLine
                    
                    """.trimIndent()
                        ++tempLineCount
                        if (tempLineCount == pageLines) {
                            tempLineCount = 0
//                            pages.add(tempPage)
                            dataBase.txtPageDao()?.insertPage(TxtPage(0, 0, tempPage))
                            tempPage = ""
                        }
                        break
                    }
                    if (tempLineCount == pageLines) {
                        tempLineCount = 0
//                        pages.add(tempPage)
                        dataBase.txtPageDao()?.insertPage(TxtPage(0, 0, tempPage))
                        tempPage = ""
                    }
                }
            }
//            println("pages is:")
//            for (i in 0 until pages.size) {
//                Log.e("page", pages[i])
//            }
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }


}